package com.hengqin.macao.activity;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.AppCompatImageView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.citybrain.rnapp.R;
import com.hengqin.macao.core.Constants;
import com.hengqin.macao.utils.MyWebChromeClient;
import com.hengqin.macao.utils.WindowsUtils;
import com.uuzuche.lib_zxing.bean.ZxingConfig;
import com.uuzuche.lib_zxing.common.Constant;

public class WebActivity extends FragmentActivity {
    private WebView webView;

    private MyWebChromeClient myWebChromeClient;

    private static String url;

    private static String host;

    public static final int CAMERA_ACTIVITY_REQUEST = 10;

    public static final int TRTC_ACTIVITY_REQUEST = 11;

    public static final int FILE_CHOOSER_RESULT_CODE = 12;

    public static final int VIDEO_REQUEST = 13;

    public static final int CAMERA_REQUEST = 14;

    public static final int FILE_CAMERA_REQUEST_PERMISSION = 15;

    public static final int CAMERA_SCAN_ACTIVITY_REQUEST = 16;

    public static final int GO_BACK_WHAT_CODE = 17;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == GO_BACK_WHAT_CODE){
                WebActivity.this.onKeyDown(KeyEvent.KEYCODE_BACK, null);
            }
        }
    };
    private TextView backIv;
    private TextView titleView;
    private String title;
    private String closeTxt;
    public  HProgressBarLoading mTopProgress;
    public TextView mTvCenterBadnet;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 系统 6.0 以上 状态栏白底黑字的实现方法
        this.getWindow()
                .getDecorView()
                .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        WindowsUtils.MIUISetStatusBarLightMode(this.getWindow(), true);
        WindowsUtils.FlymeSetStatusBarLightMode(this.getWindow(), true);
        setContentView(R.layout.web_view);

        Bundle bundle = getIntent().getExtras();
        url = bundle.getString("URL");
        host = bundle.getString("HOST");
        title = bundle.getString("Name");
        closeTxt = bundle.getString("CloseTxt");

        if (TextUtils.isEmpty(url)) {
            url = "http://172.21.64.213:8090/";
        }
        if (TextUtils.isEmpty(host)) {
            Constants.HOST = "172.16.23.231";
            Constants.PORT = "8220";
        }
        else {
//            System.out.println("@@@@host:"+host);
//            String[] str = host.split(":");
            Constants.HOST = host;
//            if(str.length>1){
//                Constants.PORT = ":" + str[1];
//            }
        }

        Constants.BASE = Constants.HOST;
        Constants.APP = Constants.BASE + "/app";

        Constants.DO_LIVE_DETECT = Constants.APP + "/upload/doLiveDetect";

        Constants.DO_TRTC_CACHE_OFF_LINE = Constants.BASE + "/trtc/doTrtcCacheOffLine";

        System.out.println("@@@@:"+Constants.BASE);

        // url = "http://172.21.64.213:8090/";
        webView = findViewById(R.id.myWebView);
        backIv = findViewById(R.id.backIv);
        titleView = findViewById(R.id.titleView);

        mTopProgress = (HProgressBarLoading) findViewById(R.id.top_progress);
        mTvCenterBadnet = (TextView) findViewById(R.id.tv_center_badnet);

        if (!TextUtils.isEmpty(title)) {
            titleView.setText(title);
        }

        if (!TextUtils.isEmpty(closeTxt)) {
            backIv.setText(closeTxt);
        }

        backIv.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                WebActivity.this.finish();
            }
        });
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setRenderPriority(RenderPriority.HIGH);
        // TUDO
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); // 设置 缓存模式

        // 开启 DOM storage API 功能
        webSettings.setDomStorageEnabled(true);
        // 开启 database storage API 功能
        webSettings.setDatabaseEnabled(true);
        String cacheDirPath = getFilesDir().getAbsolutePath() + Constants.APP_CACAHE_DIRNAME;

        // 设置数据库缓存路径
        webSettings.setDatabasePath(cacheDirPath);
        // 设置 Application Caches 缓存目录
        webSettings.setAppCachePath(cacheDirPath);
        // 开启 Application Caches 功能
        // TUDO
        // 开启 Application Caches 功能
        webSettings.setAppCacheEnabled(true);
        webSettings.setAllowFileAccess(true);

        webSettings.setBlockNetworkImage(false); // 解决图片不显示
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        myWebChromeClient = new MyWebChromeClient(this);
        webView.setWebChromeClient(myWebChromeClient);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (Build.VERSION.SDK_INT < 26) {
                    view.loadUrl(url);
                    return true;
                }
                return false;
            }

            //https的处理方式
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            //错误页面的逻辑处理
            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                // errorOperation();
            }
        });



        initCommonBind(webView);
        webView.loadUrl(url);
        checkCamerPermission();
        initDownload();
    }

    private void initDownload() {
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(final String url, String userAgent, final String contentDisposition, final String mimeType, long contentLength) {
                download(url);
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if ((requestCode != FILE_CHOOSER_RESULT_CODE && requestCode != CAMERA_REQUEST)
                || myWebChromeClient.getFilePathCallback() == null) {
            return;
        }

        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[] {
                            Uri.parse(dataString)
                    };
            }

            if (CAMERA_REQUEST == requestCode && Activity.RESULT_OK == resultCode) {
                results = new Uri[] {
                        myWebChromeClient.getCameraTakePhotoTargetUri()
                };
            }
        }

        myWebChromeClient.getFilePathCallback().onReceiveValue(results);
        myWebChromeClient.setFilePathCallback(null);
    }

    private void initCommonBind(WebView webView) {
        webView.addJavascriptInterface(new Object() {

            /**
             * 打开一个新页面
             *
             * @param href
             */
            @JavascriptInterface
            public void openPage(String href) {
                Intent intent = new Intent(WebActivity.this, WebActivity.class);
                intent.putExtra("URL", href);
                startActivity(intent);
            }

            /**
             * 打开CameraActivity
             *
             * @param paramString
             */
            @JavascriptInterface
            public void startCameraActivity(String paramString) {
                // Intent intent = new Intent(WebActivity.this, CameraActivity.class);

                // Map param = JSON.parseObject(paramString);
                // fillDataToIntent(intent, param);
                // startActivityForResult(intent, CAMERA_ACTIVITY_REQUEST);
            }

            /**
             * 打开TrtcActivity
             *
             * @param paramString
             */
            @JavascriptInterface
            public void startTrtcActivity(String paramString) {
                // Intent intent = new Intent(WebActivity.this, TrtcActivity.class);

                // Map param = JSON.parseObject(paramString);
                // fillDataToIntent(intent, param);
                // startActivityForResult(intent, TRTC_ACTIVITY_REQUEST);
            }

            /**
             * 打开TrtcActivity
             *
             */
            @JavascriptInterface
            public void startCameraScan() {
                Intent intent = new Intent(WebActivity.this, CameraScanActivity.class);
                ZxingConfig config = new ZxingConfig();
                // config.setPlayBeep(false);//是否播放扫描声音 默认为true
                //  config.setShake(false);//是否震动  默认为true
                // config.setDecodeBarCode(false);//是否扫描条形码 默认为true
                config.setReactColor(R.color.corner_color);//设置扫描框四个角的颜色 默认为白色
                // config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色
                 config.setScanLineColor(R.color.corner_color);//设置扫描线的颜色 默认白色
                config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                intent.putExtra(Constant.INTENT_ZXING_H5, "h5");
                startActivityForResult(intent, CAMERA_SCAN_ACTIVITY_REQUEST);
            }

            /**
             * 打开TrtcActivity
             *
             */
            @JavascriptInterface
            public void back() {
                Message message = Message.obtain();
                message.what = GO_BACK_WHAT_CODE;
                handler.sendMessage(message);
            }


            /**
             * 下载文件
             *
             */
            @JavascriptInterface
            public void download(String url) {
                WebActivity.this.download(url);
            }

            /**
             * 下载文件
             *
             */
            @JavascriptInterface
            public void openBrower(String url) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                intent.setData(Uri.parse(url));
                startActivity(intent);
            }

        }, "APPJS");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == FILE_CAMERA_REQUEST_PERMISSION && grantResults.length > 0) {
            // 授权成功
        }
        else {
            // 授权是吧
            this.finish();
        }
    }

    private void checkCamerPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                // 弹出对话框接收权限
                ActivityCompat.requestPermissions(this, new String[] {
                        android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        android.Manifest.permission.READ_EXTERNAL_STORAGE
                }, WebActivity.FILE_CAMERA_REQUEST_PERMISSION);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            switch (requestCode) {
                case FILE_CHOOSER_RESULT_CODE:
                case CAMERA_REQUEST:
                case VIDEO_REQUEST:
                    if (myWebChromeClient.getFilePathCallback() == null) {
                        return;
                    }
                    onActivityResultAboveL(requestCode, resultCode, data);
                    break;
                default:
                    break;
            }
            return;
        }

        switch (requestCode) {
            case CAMERA_ACTIVITY_REQUEST:
                if (data != null) {
                    Bundle bundle = data.getExtras();
                    postParamToJS("startCameraActivityCallback", bundle);
                }
                break;
            case TRTC_ACTIVITY_REQUEST:
                if (data != null) {
                    Bundle bundle = data.getExtras();
                    postParamToJS("startTrtcActivityCallback", bundle);
                }
                break;
            case FILE_CHOOSER_RESULT_CODE:
            case CAMERA_REQUEST:
            case VIDEO_REQUEST:
                if (myWebChromeClient.getFilePathCallback() == null) {
                    return;
                }
                onActivityResultAboveL(requestCode, resultCode, data);
                break;
            case CAMERA_SCAN_ACTIVITY_REQUEST:
                Bundle bundle = data.getExtras();
                postParamToJS("startCameraScanCallback", bundle);
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            // 网页可回退优先退网页
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void fillDataToIntent(Intent intent, Map param) {
        Set<String> keySet = param.keySet();
        for (String key : keySet) {
            Object value = param.get(key);
            if (value != null) {
                if (value instanceof Integer) {
                    intent.putExtra(key, (Integer) value);
                }
                else if (value instanceof String) {
                    intent.putExtra(key, (String) value);
                }
            }
        }
    }

    /**
     * 回调js统一方法
     *
     * @param method
     * @param param
     */
    private void postParamToJS(String method, Bundle param) {
        Map map = null;
        if (param != null) {
            Set<String> keySet = param.keySet();
            map = new HashMap(keySet.size());
            for (String key : keySet) {
                map.put(key, param.get(key));
            }
        }
        postParamToJS(method, map);
    }

    /**
     * 回调js统一方法
     *
     * @param method
     * @param param
     */
    private void postParamToJS(String method, Map param) {
        String paramString = "";
        if (param != null) {
            paramString = JSON.toJSONString(param);
        }
        postParamToJS(method, paramString);
    }

    private void postParamToJS(String method, String paramString) {
        paramString = paramString.replaceAll("\\\\\"", "\\\\\'"); // \"
        // 替换成
        // \'
        String url = "javascript:" + method + "('" + paramString + "')";
        webView.post(new PostRunner(url));
    }

    private class PostRunner implements Runnable {
        private String url;

        PostRunner(String url) {
            this.url = url;
        }

        @Override
        public void run() {
            webView.loadUrl(url);
        }
    }


    private void download(String url){
        // 指定下载地址
        final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        // 允许媒体扫描，根据下载的文件类型被加入相册、音乐等媒体库
        request.allowScanningByMediaScanner();
        // 设置通知的显示类型，下载进行时和完成后显示通知
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // 设置通知栏的标题，如果不设置，默认使用文件名
        // 允许在计费流量下下载
        request.setAllowedOverMetered(true);
        // 允许该记录在下载管理界面可见
        request.setVisibleInDownloadsUi(true);
        // 允许漫游时下载
        request.setAllowedOverRoaming(true);
        // 设置下载文件保存的路径和文件名
        String fileName = URLUtil.guessFileName(url, "", "");
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
        final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        // 添加一个下载任务
        long downloadId = downloadManager.enqueue(request);
    }


    /**
     * 错误的时候进行的操作
     */
    public void errorOperation() {
        //隐藏webview
        webView.setVisibility(View.INVISIBLE);
        System.out.println("加载失败");

        if (View.INVISIBLE == mTopProgress.getVisibility()) {
            mTopProgress.setVisibility(View.VISIBLE);
        }

        //3.5s 加载 0->80 进度的加载 为了实现,特意调节长了事件
        mTopProgress.setCurProgress(80, 3000, new HProgressBarLoading.OnEndListener() {
            @Override
            public void onEnd() {
                //3.5s 加载 80->100 进度的加载
                finishOperation(false);
            }
        });
    }

    /**
     * 结束进行的操作
     */
    public void finishOperation(boolean flag) {
        //最后加载设置100进度
        mTopProgress.setNormalProgress(100);
        //显示网络异常布局
        mTvCenterBadnet.setVisibility(flag ? View.INVISIBLE : View.VISIBLE);
        //点击重新连接网络
        mTvCenterBadnet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvCenterBadnet.setVisibility(View.INVISIBLE);
                //重新加载网页
                webView.reload();
            }
        });
        hideProgressWithAnim();
    }


    /**
     * 隐藏加载对话框
     */
    private void hideProgressWithAnim() {
        AnimationSet animation = getDismissAnim(WebActivity.this);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mTopProgress.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        mTopProgress.startAnimation(animation);
    }

    /**
     * 获取消失的动画
     *
     * @param context
     * @return
     */
    private AnimationSet getDismissAnim(Context context) {
        AnimationSet dismiss = new AnimationSet(context, null);
        AlphaAnimation alpha = new AlphaAnimation(1.0f, 0.0f);
        alpha.setDuration(1000);
        dismiss.addAnimation(alpha);
        return dismiss;
    }
}
